﻿using MesBSW.BLL.Mes;
using MesBSW.DAL.MesDB;
using MesBSW.Tools;
using MesBSW.View.Dialog.Mes;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace MesBSW.View.Mes
{
    public partial class SiteInfoFrm : UIPage
    {
        #region "内部变量"
        private SiteControler _ctrl = new SiteControler();
        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private List<StatusInfo> _status_list = new List<StatusInfo>();
        #endregion

        public SiteInfoFrm()
        {
            InitializeComponent();
        }

        #region "事件控件"
        /// <summary>
        /// 查询站点信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            this._status_list = this._ctrl.SearchAllProdStatus();
            this._site_list = this._ctrl.SearchAllStieInfo();
            this.InitSiteInfoTreeView();
            if (this.tvwSiteInfo.Nodes.Count > 0)
            {
                this.tvwSiteInfo.SelectedNode = this.tvwSiteInfo.Nodes[0];
            }
        }

        /// <summary>
        /// 新增站点信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddStand_Click(object sender, EventArgs e)
        {
            SiteInfo siteBean = new SiteInfo();
            siteBean.ID = 0;
            siteBean.IsDel = 0;

            SiteInfoDia tmpDia = new SiteInfoDia(siteBean);
            tmpDia.ShowDialog();

            this.SearchAfterSave();
        }

        /// <summary>
        /// 双击右边的站点列表时，弹出修改站点对话框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvSiteInfo_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvSiteInfo.Rows.Count > 0 && e.RowIndex >= 0)
            {
                int tmpInt = 0;
                DataRow tmpRow = ((DataRowView)this.dgvSiteInfo.Rows[e.RowIndex].DataBoundItem).Row;
                if (tmpRow != null && int.TryParse(tmpRow["id"].ToString(), out tmpInt))
                {
                    tmpInt = int.Parse(tmpRow["id"].ToString());
                    var query = this._site_list.Where(s => s.ID == tmpInt);
                    if (query != null && query.Count() > 0)
                    {
                        SiteInfo tmpBean = query.First();
                        SiteInfoDia tmpDia = new SiteInfoDia(tmpBean);
                        tmpDia.ShowDialog();

                        this.SearchAfterSave();
                    }
                }
            }
        }

        /// <summary>
        /// 选择左边的站点树的节点时，右边显示该站点的子站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvwSiteInfo_AfterSelect(object sender, TreeViewEventArgs e)
        {
            int tmpID = 0;
            if (int.TryParse(e.Node.Tag.ToString(), out tmpID))
            {
                tmpID = int.Parse(e.Node.Tag.ToString());
            }
            List<SiteInfo> tmpList = this._ctrl.SearchSiteInfoByParentID(tmpID);
            DataTable tmpDt = this.SiteInfoListToDataTable(tmpList);

            this.dgvSiteInfo.DataSource = tmpDt;
        }

        /// <summary>
        /// 清空界面资料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            this.DataClear();
        }

        /// <summary>
        /// 生成站点二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBarCode_Click(object sender, EventArgs e)
        {
            List<SiteInfo> printList = new List<SiteInfo>();
            string basePath = Application.StartupPath + "\\站点二维码";
            string fileName = "";

            if (!System.IO.Directory.Exists(basePath))
            {
                System.IO.Directory.CreateDirectory(basePath);
            }

            if (this.dgvSiteInfo.DataSource != null)
            {
                DataTable tmpDt = this.dgvSiteInfo.DataSource as DataTable;
                if (tmpDt != null && tmpDt.Rows.Count > 0)
                {
                    foreach (DataRow tmpRow in tmpDt.Rows)
                    {
                        var query = this._site_list.Where(s => s.ID == int.Parse(tmpRow["id"].ToString()));
                        if (query != null && query.Count() > 0)
                        {
                            var tmpSite = query.First();
                            if (tmpSite.IsDel != 1 && tmpSite.IsFinal == 1)
                            {
                                printList.Add(tmpSite);
                            }
                        }
                    }
                }
            }

            if (printList != null && printList.Count > 0)
            {
                try
                {
                    foreach (var site in printList)
                    {
                        fileName = site.SiteName + "(" + site.SiteCode + ").jpg";
                        Bitmap tmpBmp = BarCodeHook.InitQCBarCode(site.SiteCode, site.SiteName + "(" + site.SiteCode + ")", 300, 300);
                        tmpBmp.Save(basePath + "\\" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    UIMessageBox.ShowSuccess("二维码已经成功生成！");
                    Process.Start(basePath);
                }
                catch (Exception ex)
                {
                    UIMessageBox.ShowError("二维码生成失败！" + "\r\n" + ex.Message);
                }
            }
            else
            {
                UIMessageBox.ShowWarning("没有任何二维码可以生成！");
            }
        }
        #endregion

        #region "内部方法"
        /// <summary>
        /// 初始化站点树
        /// </summary>
        private void InitSiteInfoTreeView()
        {
            this.tvwSiteInfo.Nodes.Clear();
            if (this._site_list != null && this._site_list.Count > 0)
            {
                TreeNode parentNode = new TreeNode();
                parentNode.Text = "根站点";
                parentNode.Tag = 0;
                this.InitChildNode(ref parentNode, this._site_list);

                this.tvwSiteInfo.Nodes.Add(parentNode);
                this.tvwSiteInfo.ExpandAll();
            }
        }

        /// <summary>
        /// 站点树添加子节点
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="siteList"></param>
        private void InitChildNode(ref TreeNode parentNode, List<SiteInfo> siteList)
        {
            if (parentNode != null)
            {
                List<SiteInfo> childList = null;
                int tmpID = int.Parse(parentNode.Tag.ToString());
                childList = siteList.Where(s => s.ParentID == tmpID).ToList();
                if (childList != null && childList.Count > 0)
                {
                    foreach (var item in childList)
                    {
                        TreeNode childNode = new TreeNode();
                        childNode.Text = item.SiteName;
                        childNode.Tag = item.ID;
                        parentNode.Nodes.Add(childNode);
                        if (item.IsFinal != 1)
                        {
                            this.InitChildNode(ref childNode, siteList);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 将站点由List转换成DataTable
        /// </summary>
        /// <param name="siteList"></param>
        /// <returns></returns>
        private DataTable SiteInfoListToDataTable(List<SiteInfo> siteList)
        {
            DataTable resDt = new DataTable();
            resDt.Columns.Add("id");
            resDt.Columns.Add("site_code");
            resDt.Columns.Add("site_name");
            resDt.Columns.Add("site_short_name");
            resDt.Columns.Add("parent_id");
            resDt.Columns.Add("parent_name");
            resDt.Columns.Add("is_final");
            resDt.Columns.Add("is_del");
            resDt.Columns.Add("def_status");
            resDt.Columns.Add("def_status_name");
            resDt.Columns.Add("cal_point");
            resDt.Columns.Add("cal_point_name");
            resDt.Columns.Add("create_user");
            resDt.Columns.Add("create_date");
            resDt.Columns.Add("dept_id");
            if (siteList != null)
            {
                foreach (SiteInfo site in siteList)
                {
                    DataRow addRow = resDt.NewRow();
                    addRow["id"] = site.ID;
                    addRow["site_code"] = site.SiteCode;
                    addRow["site_name"] = site.SiteName;
                    addRow["site_short_name"] = site.SiteShortName;
                    addRow["parent_id"] = site.ParentID;
                    addRow["dept_id"] = site.deptId;
                    if (site.ParentID <= 0)
                    {
                        addRow["parent_name"] = "根站点";
                    }
                    else
                    {
                        var query = this._site_list.Where(s => s.ID == site.ParentID);
                        if (query != null && query.Count() > 0)
                        {
                            addRow["parent_name"] = query.First().SiteName;
                        }
                    }
                    addRow["is_final"] = site.IsFinal == 1 ? false : true;
                    addRow["is_del"] = site.IsDel == 1 ? true : false;
                    addRow["cal_point"] = site.CalPoint;
                    if (site.CalPoint != null && site.CalPoint.Equals("B"))
                    {
                        addRow["cal_point_name"] = "开始时间点";
                    }
                    else if (site.CalPoint != null && site.CalPoint.Equals("E"))
                    {
                        addRow["cal_point_name"] = "结束时间点";
                    }
                    else
                    {
                        addRow["cal_point_name"] = "非计算时间";
                    }
                    addRow["def_status"] = site.DefStatus;
                    if (this._status_list != null && this._status_list.Count > 0)
                    {
                        var query = this._status_list.Where(s => s.ID == site.DefStatus);
                        if (query != null && query.Count() > 0)
                        {
                            addRow["def_status_name"] = query.First().StatusValue;
                        }
                    }
                    addRow["create_user"] = site.CreateUser;
                    addRow["create_date"] = site.CreateDate;
                    resDt.Rows.Add(addRow);
                }
            }
            return resDt;
        }

        /// <summary>
        /// 保存成功后，查询所有的站点设置
        /// </summary>
        private void SearchAfterSave()
        {
            this._status_list = this._ctrl.SearchAllProdStatus();
            this._site_list = this._ctrl.SearchAllStieInfo();
            this.InitSiteInfoTreeView();
            if (this.tvwSiteInfo.Nodes.Count > 0)
            {
                this.tvwSiteInfo.SelectedNode = this.tvwSiteInfo.Nodes[0];
            }
        }

        /// <summary>
        /// 清空界面资料
        /// </summary>
        private void DataClear()
        {
            this._site_list = new List<SiteInfo>();
            this.tvwSiteInfo.Nodes.Clear();
            this.dgvSiteInfo.DataSource = this.SiteInfoListToDataTable(this._site_list);
        }
        #endregion
    }
}
